import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { Link, useLocation } from "react-router-dom";
import "./index.scss";
import { getArticleDetailApi, editArticleApi } from "@/apis/article";
import { useEffect, useRef, useState } from "react";

//富文本编辑器
import ReactQuill from "react-quill-new";
import "react-quill-new/dist/quill.snow.css";

//发布文章
import { 
    addArticleApi,
 } from "@/apis/article";

 import useChannel from "@/hooks/useChannel";

const { Option } = Select;
const Publish = () => {
  
  const [messageApi, contextHolder] = message.useMessage();
  //频道列表
  const { channelList } = useChannel();
  //发布文章
  const onFinish = (values) => {
    if (imgType !== fileList.length) 
      return messageApi.open({
        type: 'warning',
        content: '图片类型和数量不一致',
      });
    console.log(values);
    const { channel_id, title, content } = values;
    const params = {
      title,
      channel_id,
      content,
      cover: {
        type: imgType,
        images:imgType === 0 ? [] : fileList.map((item) => {
            if (item.response) {
                return item.response.data.url
            } else {
                return item.url
            }
    
        }),
      },
    };
    if(id){
      params.id = id;
      editArticleApi(params).then((res) => { 
        messageApi.open({
          type: 'success',
          content: '文章修改成功',
        });
      });
    }else{
      addArticleApi(params).then((res) => {
        messageApi.open({
          type: 'success',
          content: '文章发布成功',
        });
      });
    }
    
  };

  const cacheList = useRef([]);
  const [fileList, setFileList] = useState([]);
  //图片类型
  const [imgType, setImgType] = useState(1);
  const handleImgTypeChange = (type) => { 
    setImgType(type)
    if(type === 1){
        const list = cacheList.current[0]? [cacheList.current[0]] : []
        setFileList(list)
    }else if(type === 3){
        setFileList(cacheList.current)
    }
  };
  const handleUploadChange = ({ fileList }) => {
    console.log("上传完",fileList)
    setFileList(fileList)
    cacheList.current = fileList
  }

  const [form] = Form.useForm();
  const location = useLocation();
  console.log("location",location);

  const id = location.search?.split("=")[1]
  
  useEffect(() => { 
    //是否为编辑状态
    if(id){
      getArticleDetailApi(id).then(res => { 
        form.setFieldsValue({
          ...res.data,
          type: res.data.cover.type
        });
        setImgType(res.data.cover.type)
        // setFileList(res.data.cover.images)
        const imgList = res.data.cover.images.map(url => {
          return { url }
        })
        setFileList(imgList)
        cacheList.current = imgList
  
      })

    }
  }, [id, form]);

  const title = id ? "编辑文章" : "发布文章";

  return (
    <div className="publish">
      {contextHolder}
      <Card
        title={
          <Breadcrumb
            items={[
              { title: <Link to={"/"}>首页</Link> },
              { title: title },
            ]}
          />
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: "请输入文章标题" }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: "请选择文章频道" }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {channelList.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
              {/* <Option value={0}>推荐</Option> */}
            </Select>
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={(e) => handleImgTypeChange(e.target.value)}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imgType > 0 && (
              <Upload 
              name="image"
              listType="picture-card" 
              showUploadList 
              fileList={fileList}
              maxCount={imgType}
              onChange={handleUploadChange}
              action={'http://geek.itheima.net/v1_0/upload'}
              >
                {fileList.length >= imgType ? null : (<div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>)}
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: "请输入文章内容" }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                发布文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Publish;
